package com.shuaigef.springbootinit.utils;

import com.shuaigef.springbootinit.common.PageResult;

import java.util.List;

/**
 * 分页工具类
 *
 * @author <a href="https://github.com/shuaigef">shuaigef</a>
 */
public class PageUtils {

    /**
     * 分页
     *
     * @param list      列表数据
     * @param current   当前页码
     * @param pageSize  每页大小
     * @param <T>      泛型
     * @return         分页结果
     */
    public static <T> PageResult<T> paginate(List<T> list, long current, long pageSize) {
        if (list == null || list.isEmpty()) {
            return PageResult.<T>builder()
                    .records(list)
                    .total(0L)
                    .current(current)
                    .pageSize(pageSize)
                    .build();
        }

        long total = list.size();
        long start = (current - 1) * pageSize;
        long end = Math.min(start + pageSize, total);

        // 如果开始位置大于总数，返回空列表
        if (start > total) {
            return PageResult.<T>builder()
                    .records(list.subList(0, 0))
                    .total(total)
                    .current(current)
                    .pageSize(pageSize)
                    .build();
        }

        return PageResult.<T>builder()
                .records(list.subList((int) start, (int) end))
                .total(total)
                .current(current)
                .pageSize(pageSize)
                .build();
    }
} 